package com.bigfans.userservice.service.impl;

import com.bigfans.framework.dao.BaseServiceImpl;
import com.bigfans.framework.event.ApplicationEventBus;
import com.bigfans.model.event.user.AddressCreatedEvent;
import com.bigfans.userservice.dao.AddressDAO;
import com.bigfans.userservice.model.Address;
import com.bigfans.userservice.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 
 * @Description:用户配送地址服务类
 * @author lichong
 * 2014年12月16日下午11:26:21
 *
 */
@Service(AddressServiceImpl.BEAN_NAME)
public class AddressServiceImpl extends BaseServiceImpl<Address> implements AddressService {

	public static final String BEAN_NAME = "addressService";
	
	private AddressDAO addressDAO;
	@Autowired
	private ApplicationEventBus eventBus;

	@Autowired
	public AddressServiceImpl(AddressDAO addressDAO) {
		super(addressDAO);
		this.addressDAO = addressDAO;
	}

	@Override
	@Transactional
	public void create(Address e) throws Exception {
		super.create(e);
		eventBus.publishEvent(new AddressCreatedEvent(e.getId()));
	}

	@Override
	@Transactional(readOnly=true)
	public List<Address> listByUser(String userId) throws Exception {
		return addressDAO.listByUser(userId);
	}
	
	@Override
	@Transactional(readOnly=true)
	public Address getUserAddress(String addressId, String userId) throws Exception {
		return addressDAO.getByUser(addressId, userId);
	}
	
	@Override
	@Transactional(readOnly=true)
	public Address getUserDefaultAddress(String userId) throws Exception {
		Address example = new Address();
		example.setUserId(userId);
		example.setIsPrimary(true);
		return this.load(example);
	}
	
	@Override
	@Transactional(readOnly=true)
	public Address getSysDefaultAddress() throws Exception {
		Address address = new Address();
		address.setId("1");
		address.setAddress("辽宁省大连市高新园区");
		return address;
	}

	@Override
	@Transactional
	public int delete(String uid, String addrId) throws Exception {
		Address example = new Address();
		example.setId(addrId);
		example.setUserId(uid);
		return super.delete(example);
	}
	
	@Override
	@Transactional
	public int update(Address e) throws Exception {
		Address loadedAddr = super.load(e.getId());
		if(loadedAddr.getUserId() != e.getUserId()){
			throw new Exception("更新失败,你不能更新非法记录.");
		}
		return super.update(e);
	}
	
}
